# -*- coding: utf-8

import requests
import time
from datetime import datetime
import random
import re
import sys

INFLUXDB_API = "http://192.168.11.200:8086/api/v2/write?org=prewater&bucket=gold&precision=s"
INFLUXDB_TOKEN = sys.argv[1]

API_1 = "https://api.jijinhao.com/sQuoteCenter/realTime.htm"
API_1_Param = {
    "code": "JO_42760",
}
# API_2 = "curl http://quote.zhijinwang.com/zhijinwang_all1.asp?rnd=0.07219367633343388"
API_2 = "http://quote.zhijinwang.com/zhijinwang_all1.asp"
API_2_Factor = 0.9


def write_influxdb(lines: []):
    line_join = '\n'.join(lines)
    headers = {
        "Authorization": "Token {}".format(INFLUXDB_TOKEN),
        "Content-Type": "text/plain; charset=utf-8",
        "Accept": "application/json",
    }



    resp = requests.post(INFLUXDB_API, headers=headers, data=line_join)
    if resp.status_code != 200:
        print(resp.text)


def get_api_1():
    payload = {"code": API_1_Param["code"], "_": str(int(time.time() * 1000))}
    header = {"Referer": "http://quote.cngold.org/"}
    resp = requests.get(API_1, headers=header, params=payload, timeout=(0.5, 0.5))
    if resp.status_code != 200:
        print(resp.text)
        return None
    else:
        # returned text like
        # 看看
        # var hq_str = "工行纸黄金(人民币),0,363.45,363.63,363.69,360.65,0,0,2540.0,0.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2021-09-24,12:13:22,000.0495,0.0,0.0,363.32,100,2021-09-24,12:13:21,";
        # the float numbers:
        # 1: 昨日收, 2: 实时价格 bank_buy，3: 最高, 4: 最低
        print(resp.text)
        str_split = resp.text.split("=")[-1].split(',')
        current = float(str_split[3])
        date_str = str_split[-3]
        time_str = str_split[-2]
        date_time = datetime.strptime(date_str + " " + time_str, "%Y-%m-%d %H:%M:%S")
        print(date_time)
        return current, date_time


def get_api_2():
    payload = {"rnd": "%.16f" % random.random()}
    resp = requests.get(API_2, params=payload)
    if resp.status_code != 200:
        print("get {} error".format(resp.url))
        return None
    resp.encoding = 'GBK'
    #   <tr>
    # <td align="center" height="22" style="BORDER: 1px solid #CCCCCC;margin:0 auto;" cellspacing="0px" cellpadding="3"><font size="2"><a target="_top" href="http://gold.zhijinwang.com">纸黄金</a></font></td>
    # <td align="center" height="22" style="BORDER: 1px solid #CCCCCC;margin:0 auto;" cellspacing="0px" cellpadding="3"><font size="2" color="#FF0000">364.35</font></td>
    # </tr>
    match = re.compile(r' href="http://gold\.zhijinwang\.com">纸黄金</a>')
    lines = resp.text.split('\r\n')
    i = 0
    while i < len(lines):
        if match.search(lines[i]):
            break
        i += 1
    # because is i add 1, so if no find, i is equal the length of lines
    if i == len(lines):
        print("not found value after search all content")
        return None
    matched = re.match(r'.*?>(\d{3,5}\.\d{2})</font></td>$', lines[i + 1])
    if matched:
        return float(matched.group(1)) - API_2_Factor / 2
    else:
        print("not found value in returned content")
        return None


if __name__ == '__main__':
    while True:
        try:
            result = get_api_1()
            if result is None:
                continue
            value, date_time = result
            print("{} {}".format(value, date_time))
            lines = [
                "papergold,bank=icbc,price_t=median price={} {}".format(value, int(date_time.timestamp())),
                    ]
            # write_influxdb(lines)
        except Exception as e:
            print(e)
            continue

        time.sleep(3)
